import {
  Controller,
  Get,
  Post,
  Body,
  ALL,
  Inject,
  Provide,
  Del,
  Put,
  Patch,
  Query,
} from '@midwayjs/decorator';

import {
  CreateCustomerDto,
  UpdateCustomerDto,
  CustomerPageDto,
} from '../dto/customer';

import { BaseController, ERRCODE } from '../../../comm/controller';
import { CustomerService } from '../service/customer';

@Provide()
@Controller('/mall/customer')
export class MallCustomerController extends BaseController {
  @Inject()
  customerService: CustomerService;

  @Post('/add')
  async add(@Body(ALL) customer: CreateCustomerDto) {
    try {
      const data = await this.customerService.add(customer);
      return this.ok({ customer: data });
    } catch (err) {
      return this.fail(ERRCODE.SERVER_COMM_ERROR, err.message);
    }
  }

  /**
   * 事务：
   * - 删除 customer 记录
   * - 删除 address, cart, order 相关记录
   * - 删除 collect, history 信息
   */
  @Post('/delete')
  @Del('/delete')
  async delete(@Body('id') customerId) {
    try {
      await this.customerService.delete(customerId);
      return this.ok({});
    } catch (err) {
      return this.fail(ERRCODE.SERVER_COMM_ERROR, err.message);
    }
  }

  @Post('/update')
  @Put('/update')
  @Patch('/update')
  async update(@Body(ALL) customer: UpdateCustomerDto) {
    try {
      const data = await this.customerService.update(customer);
      return this.ok({ customer: data });
    } catch (err) {
      return this.fail(ERRCODE.SERVER_COMM_ERROR, err.message);
    }
  }

  @Get('/info')
  async info(@Query('id') customerId: number) {
    try {
      const data = await this.customerService.info(customerId);
      return this.ok({ customer: data });
    } catch (err) {
      return this.fail(ERRCODE.SERVER_COMM_ERROR, err.message);
    }
  }

  @Get('/page')
  async page(@Query(ALL) pageOp: CustomerPageDto) {
    try {
      const data = await this.customerService.page(pageOp);
      return this.ok({ customers: data });
    } catch (err) {
      return this.fail(ERRCODE.SERVER_COMM_ERROR, err.message);
    }
  }
}
